package com.itic.mall.system.orders.detail.service;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.type.*;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.goods.goodsspu.service.GoodsSpuService;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSku;
import com.itic.mall.system.inter.orders.detail.persistence.dao.OrdersDetailDao;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetailExample;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetailExample.Criteria;
import com.itic.mall.system.inter.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.inter.orders.orderJD.persistence.dao.OrderJDDao;
import com.itic.mall.system.inter.orders.orderJDLeadInto.persistence.dao.OrderJDLeadIntoDao;
import com.itic.mall.system.inter.users.giveMoney.persistence.model.UsersGiveMoney;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.project.score.service.ProjectScoreService;
import com.itic.mall.system.service.StoreInfoService;
import com.itic.mall.system.users.giveMoney.service.UsersGiveMoneyService;
import com.itic.mall.system.users.pointslog.service.UsersPointslogService;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import com.itic.mall.system.users.usersmall.service.UsersMallService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class OrdersDetailService
     extends CrudService<OrdersDetailDao,OrdersDetail,OrdersDetailExample> {
    @Autowired
    private OrdersDetailDao ordersDetailDao;
    @Autowired
    private OrderJDLeadIntoDao orderJDLeadIntoDao;
    @Autowired 
    private OrderJDDao orderJDDao;
    @Autowired
    private OrdersItemService ordersItemService;
    @Autowired
    private PayUserlogService payUserlogService;
    @Autowired
    private UsersPointslogService usersPointslogService;
    @Autowired
    private UsersCouponService usersCouponService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private UsersMallService usersMallService;
    @Autowired
    private StoreInfoService storeInfoService;
    @Autowired
    private GoodsSpuService goodsSpuService;
    @Autowired
    private UsersGiveMoneyService usersGiveMoneyService;
    @Autowired
    private ProjectScoreService projectScoreService;
    
    public String addOrderDetail(Double deducScore, Integer score,double sumAmount,String isUsePoints,String userNickName,String orderNo,Double expressFee,double actualPay,String yunId,String userId,String addressId ,String couponId,String buyMsg) {
    	OrdersDetail ordersDetail = new OrdersDetail();
    	ordersDetail.setYunUserId(yunId);
		ordersDetail.setUserId(userId);
		ordersDetail.setAddressId(addressId);
		ordersDetail.setSumAmount(sumAmount); 
		ordersDetail.setActualPay(actualPay);
		//添加运费
		if(expressFee!=null)
			ordersDetail.setExpressFee(expressFee);
		ordersDetail.setState(OrderType.Paying.getState());
		ordersDetail.setCouponId(couponId);
		ordersDetail.setStartTime(new Date());
		ordersDetail.setOrderNo(orderNo);
		ordersDetail.setType("0");// 默认友惠家
		ordersDetail.setIsDelete(DBConst.TRUE);
		ordersDetail.setUserNickName(userNickName);
		ordersDetail.setIsUsePoints(isUsePoints);
		if(isUsePoints!=null &&"1".equals(isUsePoints)) {
			ordersDetail.setScore(score);
			ordersDetail.setDeducScore(deducScore);
		}else {
			ordersDetail.setScore(0);
			ordersDetail.setDeducScore(0.0);
		}
		ordersDetail.setCouponId(couponId);
		ordersDetail.setCustomNote(buyMsg);
		String result = this.add(ordersDetail);
		return result;
    }
    
    public OrdersDetail getOrdersDetailByOrderNo(String orderNo) {
    	OrdersDetailExample example = new OrdersDetailExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andOrderNoEqualTo(orderNo);
    	//TODO  是否效验订单过期
    	List<OrdersDetail> ordersDetails = this.list(example);
    	if(ordersDetails.isEmpty())
    		return null;
    	else 
    		return ordersDetails.get(0);
    }
    
    //TODO 封装各种支付成功后的业务
    public String aliPaySuccess(String orderNo,String payNo,PayType payType,Date payTime) {
    	OrdersDetail ordersDetail = this.getOrdersDetailByOrderNo(orderNo);
    	if(ordersDetail!=null && OrderType.Paying.getState().equals(ordersDetail.getState())) {
    		UsersMall user = this.usersMallService.get(ordersDetail.getUserId());
    		String yunId=ordersDetail.getYunUserId();
    		if(yunId == null) {
    			if(user.getType()!=null && UserType.isYDZ(user.getType()))
    				yunId = user.getId();
    			else
    				yunId = user.getYunId();
    		}
    		UsersMall yunUser = this.usersMallService.get(yunId);
    		// 支付成功 更改ordersDetail 订单状态
    		ordersDetail.setState(OrderType.Sending.getState());
    		ordersDetail.setPayNo(payNo);
    		ordersDetail.setPayType(payType.getType());
    		this.edit(ordersDetail);
    		//扣积分 
    		if("1".equals(ordersDetail.getIsUsePoints())) 
    			this.usersPointslogService.dealUsersPointsLog(ordersDetail.getUserId(), OperateType.sub	, ordersDetail.getScore(),ordersDetail.getOrderNo());
    		//TODO 加积分
    		this.addUsersScore(user, ordersDetail.getActualPay(), orderNo);
    		//  扣系统优惠券 
    		if(StringUtils.isNotEmpty(ordersDetail.getCouponId()))
    			 this.usersCouponService.subUsersCouponByCouponId(ordersDetail.getCouponId());
    		//计算店主的销售额
    		double actualMoney = ordersDetail.getActualPay()==null?0:ordersDetail.getActualPay();
    		if(yunUser!=null)
    			this.storeInfoService.calTotalSale(yunUser.getId(), actualMoney);
    		//如果自己是店主 填加自己的销售额 
    		/*if(UserType.isYDZ(user.getType()) &&ordersDetail.getYunUserId()!=null && !user.getId().equals(ordersDetail.getYunUserId()))
    			this.storeInfoService.calTotalSale(user.getId(), actualMoney);*/
    		// 更改OrderItem中未待支付状态的订单状态
    		List<OrdersItem> ordersItems = this.ordersItemService.getOrderItemsByOrderNo(orderNo);
    		this.payUserlogService.addPayAmount(user.getId(), FinanceType.Pay, ordersDetail.getActualPay(), payType, orderNo, payNo, payTime);
    		for(OrdersItem item : ordersItems){
    			if(OrderType.Paying.getState().equals(item.getState())) {
    				item.setState(OrderType.Sending.getState());
    				this.ordersItemService.edit(item);
    				//减少库存
    				this.goodsSpuService.getCouponNumById( item.getSkuId(),"sub",item.getCount());
    				//扣商品的优惠券
    				//if(StringUtils.isNotEmpty(item.getCouponId()))
    				//	this.usersCouponService.subUsersCouponByCouponId(item.getCouponId());
    				// 计算云店主的佣金
    				GoodsSku sku = this.goodsSkuService.get(item.getSkuId());
    				//云店主添加收益记录PayUserLog+
    				if(yunUser !=null) {
    					String profitAmount = sku.getSkuProfit()==null?"0":sku.getSkuProfit().toString();
    					int count = item.getCount()==null?1:item.getCount();
    					this.payUserlogService.addUserTeamPreProfit(yunUser, profitAmount, TaxCompany.yh, orderNo, PreType.pre, PreIncomeChannel.yh, sku.getId(),OperateType.add,PreIncomeType.Commission,count);
    				}
    				
    			}
    		}
    		return SUCCESS;
    	}else
    		return FAILED;
    }
    
    public String addUsersScore(UsersMall usersMall,double consume,String orderNo) {
    	int score = this.projectScoreService.calGiveUserScore(consume);
    	return this.usersPointslogService.dealUsersPointsLog(usersMall.getId(), OperateType.add, score, orderNo);
    }
    /**
     * 获取用户最近的下单
     * @param userId
     * @param date
     * @return
     */
    public List<OrdersDetail> findUserLateDateOrdersDetail(String userId,Date date){
    	OrdersDetailExample example = new OrdersDetailExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	if(date!=null)
    		criteria.andCreateTimeGreaterThan(date);
    	criteria.andLivingTypeEqualTo("1");
    	List<OrdersDetail> ordersDetails = this.list(example);
    	return ordersDetails;
    }
    
    public List<OrdersDetail> findUserLateDateNotExistOrdersDetail(String userId,Date date){
    	OrdersDetailExample example = new OrdersDetailExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	criteria.andCreateTimeGreaterThan(date);
    	List<OrdersDetail> ordersDetails = this.list(example);
    	return ordersDetails;
    }
    /**
     * 获取用户的所有订单记录
     * @param userId
     * @return
     */
    public List<OrdersDetail> findUserLateDateOrdersDetail(String userId){
    	OrdersDetailExample example = new OrdersDetailExample();
    	Criteria criteria = example.createCriteria();
    	criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    	criteria.andUserIdEqualTo(userId);
    	criteria.andLivingTypeEqualTo("1");
    	List<OrdersDetail> ordersDetails = this.list(example);
    	return ordersDetails;
    }
    /**
	 * 获取用户总的消费金额和消费笔数
	 * @param userId
	 * @return
	 */
	public Map<String, Object>  getUserTotalCousume(String userId) {
		Map<String, Object> data = new HashMap<>();
		double consume = 0;
		List<UsersGiveMoney> usersGiveMoneys = this.usersGiveMoneyService.findMoneyByUserId(userId);
		for(UsersGiveMoney usersGiveMoney : usersGiveMoneys)
			consume +=usersGiveMoney.getConsume()==null?0:usersGiveMoney.getConsume();
		List<OrdersDetail> ordersDetails = this.findUserLateDateOrdersDetail(userId);
		for(OrdersDetail detail : ordersDetails)
			consume +=detail.getActualPay();
		data.put("consume", consume);
		int totalSize= ordersDetails.size()+usersGiveMoneys.size();
		data.put("consumeCount", totalSize);
		return data;
	}
	/**
	 * 
	 * @param userId
	 * @return
	 */
	public List<String> getOrderNos(String yunUserId){
		List<String> backOrderNos = new ArrayList<String>();
		List<String> orderNos = this.ordersDetailDao.getOrderNos(yunUserId);//友惠家订单
		List<String> jdPreOrderNos = this.orderJDLeadIntoDao.getPreOrderNums(yunUserId);//京东预估订单
		List<String> jdActualOrderNos = this.orderJDDao.getOrderNums(yunUserId);//京东累计订单
		if(orderNos.size()>0){
			backOrderNos.addAll(orderNos);
		}
		if(jdActualOrderNos.size()>0){
			backOrderNos.addAll(jdActualOrderNos);
		}
		if(jdPreOrderNos.size()>0){
			backOrderNos.addAll(jdPreOrderNos);
		}
		return backOrderNos;
	}
}